package edu.zqu.file.project.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

import edu.zqu.file.project.service.UploadService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
 * @Author 吴典秋
 * @Date 2020/4/17 21:40
 * @Description:
 * @Version 1.0
 */
@Service
public class UploadServiceImpl implements UploadService {

    Logger logger = LoggerFactory.getLogger(getClass());

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadServiceImpl.class);

    private static final List<String> CONTENT_TYPE =
            Arrays.asList
                    ("image/jpeg", "image/gif", "image/png", "application/x-png",
                            "application/x-rar-compressed");

    @Autowired
    private FastFileStorageClient storageClient;

    @Override
    public String uploadImage(MultipartFile file) {
        //校验文件类型
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if (!CONTENT_TYPE.contains(contentType)) {
            System.out.println(contentType);
            LOGGER.info("文件类型不合法:{}", originalFilename);
            return null;
        }
        try {
            /**
             * 校验文件内容-图片
             */
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                LOGGER.info("文件内容不合法:{}", originalFilename);
                return null;
            }
            /**
             * 保存到fastDFS
             */
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath path = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            /**
             * 返回url,进行回显
             */
            logger.info(path.getFullPath());
            return path.getFullPath();
        } catch (IOException e) {
            LOGGER.info("服务器内部错误:{}", originalFilename);
            e.printStackTrace();
        }
        return null;
    }

    public byte[]  download(String fileUrl) {
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        logger.info(group);
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());
        return bytes;
    }
}